package alarm

import (
	"strconv"
	"strings"
	"system-admin/config/mysql"
	"system-admin/internal/models"

	"github.com/samber/lo"
)

// FixAlarmType 告警类型变动处理
func FixAlarmType() {
	var rules []models.AlarmNotifyRule
	mysql.NewDB().Model(&models.AlarmNotifyRule{}).Find(&rules)
	for _, rule := range rules {
		alarmTypes := strings.Split(rule.AlarmTypes, ",")
		// 替换原来的告警类型定义
		for k, alarmType := range alarmTypes {
			alarmTypeInt, _ := strconv.Atoi(alarmType)
			if alarmTypeInt == 50 {
				alarmTypes[k] = "2001"
			} else if alarmTypeInt == 51 {
				alarmTypes[k] = "2002"
			} else if alarmTypeInt == 52 {
				alarmTypes[k] = "2003"
			}
		}
		if !lo.Contains(alarmTypes, "2004") {
			alarmTypes = append(alarmTypes, "2004")
		}
		if !lo.Contains(alarmTypes, "2005") {
			alarmTypes = append(alarmTypes, "2005")
		}
		if !lo.Contains(alarmTypes, "2006") {
			alarmTypes = append(alarmTypes, "2006")
		}
		if !lo.Contains(alarmTypes, "2007") {
			alarmTypes = append(alarmTypes, "2007")
		}
		if !lo.Contains(alarmTypes, "2008") {
			alarmTypes = append(alarmTypes, "2008")
		}
		if !lo.Contains(alarmTypes, "2009") {
			alarmTypes = append(alarmTypes, "2009")
		}
		if !lo.Contains(alarmTypes, "2010") {
			alarmTypes = append(alarmTypes, "2010")
		}
		if !lo.Contains(alarmTypes, "2011") {
			alarmTypes = append(alarmTypes, "2011")
		}
		if !lo.Contains(alarmTypes, "2012") {
			alarmTypes = append(alarmTypes, "2012")
		}
		mysql.NewDB().Model(&models.AlarmNotifyRule{}).Where("id = ?", rule.ID).Update("alarm_types", strings.Join(alarmTypes, ","))
	}
}

// FixNotifyRecords 修复告警记录中的类型
func FixNotifyRecords() {
	db := mysql.NewDB()
	db.Model(&models.AlarmNotifyRecord{}).Where("alarm_type = ?", 50).Update("alarm_type", 2001)
	db.Model(&models.AlarmNotifyRecord{}).Where("alarm_type = ?", 51).Update("alarm_type", 2002)
	db.Model(&models.AlarmNotifyRecord{}).Where("alarm_type = ?", 52).Update("alarm_type", 2003)
}
